package cn.mengfly.testnrz.curator;

import lombok.Data;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

import java.io.Closeable;
import java.io.IOException;

/**
 * create by 尼恩 @ 疯狂创客圈
 *
 * @author Mengfly
 */
@Data
public class SnowflakeIdWorker implements Closeable {
    private static final String ZK_ADDRESS = "127.0.0.1:2181";

    /**
     * Zk客户端
     */
    private CuratorFramework client = null;

    /**
     * 工作节点的路径
     */
    private String pathPrefix = "/test/IDMaker/worker-";
    private String pathRegistered = null;

    private static SnowflakeIdWorker instance = null;

    public static SnowflakeIdWorker inst() {
        if (instance == null) {
            instance = new SnowflakeIdWorker();
            instance.client = ClientFactory.createSimple(ZK_ADDRESS);
            instance.init();
        }
        return instance;
    }

    private SnowflakeIdWorker() {

    }

    public void init() {
        // 创建一个 ZNode 节点
        // 节点的 payload 为当前worker 实例
        try {
            client.start();
            pathRegistered = client.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                    .forPath(pathPrefix);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public long getId() {
        String sid = null;
        if (null == pathRegistered) {
            throw new RuntimeException("节点注册失败");
        }
        int index = pathRegistered.lastIndexOf(pathPrefix);
        if (index >= 0) {
            index += pathPrefix.length();
            sid = index <= pathRegistered.length() ? pathRegistered.substring(index) : null;
        }

        if (null == sid) {
            throw new RuntimeException("节点ID生成失败");
        }

        return Long.parseLong(sid);

    }

    @Override
    public void close() throws IOException {
        client.close();
    }
}